package com.itheima.ums.interceptor;

import com.itheima.mall.pojo.Admin;
import com.itheima.mall.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class TokenInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1、判断token是否合法
        String token = request.getHeader("Authorization");

        if (token != null){
            token = token.replace("Bearer ", "");
            //4、如果token正常可用，放行
            //解析token，获取id和手机号码，
            Claims claims = JwtUtils.getClaims(token);
            String username = (String) claims.get("username");
            Integer id = (Integer) claims.get("id");
            Admin admin = new Admin();
            admin.setId(Long.valueOf(id));
            admin.setUsername(username);
            AdminHolder.set(admin);
        }

/*
        boolean verifyToken = JwtUtils.verifyToken(token);
        if (!verifyToken) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }
*/
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        AdminHolder.remove();
    }
}
